<template>
    <div class="com-container">
        <div class="header">
            <div class="title">静态结果偏离监控</div>
            <div class="operate">
                <el-button
                    :loading="compareLoading"
                    size="mini"
                    style="margin: 0 10px 0 0"
                    class="btn-compare"
                    type="primary"
                    @click="handleBtn('compare')"
                    >比对</el-button
                >
                <!-- <el-button @click="operateStatus = '0'">变0!停!</el-button> -->
            </div>
        </div>

        <div class="content">
            <!-- 饼图 -->
            <div class="pie-content">
                <div v-for="(item, key) in pieData" :key="key" :class="['pie-content-item-' + key, 'pie-content-item']">
                    <el-card>
                        <div class="text">
                            <div class="text-left">
                                <div class="imgStyle pieImg"></div>
                                <span>{{ item.name }}</span>
                            </div>
                        </div>
                        <div class="pie-content-chart">
                            <StaticResultPie :echartData="item" :ref="key"></StaticResultPie>
                        </div>
                    </el-card>
                </div>
            </div>

            <!-- 柱状图 -->
            <div class="bar-content">
                <el-card>
                    <div class="text">
                        <div class="text-left">
                            <div class="imgStyle barImg"></div>
                            <span>各类型条目·条目结果/明细结果差异情况</span>
                        </div>
                        <div class="bar-content-operate">
                            <el-button size="mini" @click="handleBtn('item')" :type="currentBtn == 'item' ? 'primary' : ''">条目</el-button>
                            <el-button size="mini" @click="handleBtn('detail')" :type="currentBtn == 'detail' ? 'primary' : ''">明细</el-button>
                        </div>
                    </div>

                    <div class="bar-content-chart">
                        <StaticBar :echartData="specificData[currentBtn]" type="bar-content" ref="diffBar"></StaticBar>
                    </div>
                </el-card>
            </div>

            <!-- 表格 -->
            <div class="table-content">
                <el-card>
                    <div class="text">
                        <div class="text-left">
                            <div class="imgStyle tableImg"></div>
                            <span>{{ currentType === 'item' ? '条目对比结果数据详情' : '条目明细结果数据详情' }} </span>
                            <span style="margin-left: 30px">操作员: {{ tableInfo.operateUserName }}</span>
                            <span style="margin-left: 30px">操作时间：{{ tableInfo.operateDateTime }}</span>
                        </div>
                        <div>
                            <el-checkbox v-model="tableQueryParams.exceedThreshold" @change="changeExceedThreshold">
                                <span>偏离度≥</span>
                                <el-input
                                    size="mini"
                                    style="width: 60px"
                                    @input="handleDeviationRatio"
                                    v-model="tableQueryParams.deviationRatio"
                                ></el-input>
                                <span>%</span>
                            </el-checkbox>

                            <el-button
                                size="mini"
                                style="margin-left: 10px"
                                @click="handleCutTable('item')"
                                :type="currentType == 'item' ? 'primary' : ''"
                            >
                                条目
                            </el-button>
                            <el-button size="mini" @click="handleCutTable('detail')" :type="currentType == 'detail' ? 'primary' : ''">明细</el-button>
                            <!-- <el-button v-show="currentType === 'item'" size="mini" type="primary" @click="queryStatic">查询</el-button> -->
                            <!-- <el-select size="mini" style="width:160px;margin:0 6px" v-model="tableQueryParams.type"></el-select> -->
                            <!-- <el-button size="mini" type="primary" style="margin-left: 10px" @click="handleBtn('loadout')">da导出</el-button> -->
                            <el-button size="mini" type="primary" @click="handleBtn('loadout1')">导出</el-button>
                        </div>
                    </div>
                    <div v-show="currentType === 'item'" class="table-content-data">
                        <RiskTableP
                            ref="risk-table-item"
                            :tableConfig="tableConfig"
                            :tableData="tableDataItem"
                            :paging="pagingItem"
                            :column="tableColumnsItem"
                            :contentHeight="'calc(100%  - 32px)'"
                            :searchParams="tableQueryParamsItem"
                            v-loading="tableLoadingItem"
                            @page-change="pageChangeItem"
                        >
                        </RiskTableP>
                    </div>
                    <div v-show="currentType === 'detail'" class="table-content-data">
                        <RiskTableP
                            ref="risk-table"
                            :tableConfig="tableConfig"
                            :tableData="tableData"
                            :paging="paging"
                            :column="tableColumns"
                            :contentHeight="'calc(100%  - 32px)'"
                            :searchParams="tableQueryParams"
                            v-loading="tableLoading"
                            @page-change="pageChange"
                        >
                            <template #stockCodes="{ row }">
                                <el-tooltip placement="bottom" popper-class="tips-popper">
                                    <div slot="content" v-if="row.hasOwnProperty('stockCodes') && row.stockCodes.length > 1">
                                        <!-- <span v-for="(item, index) in row.stockCodes" :key="index">
                                            {{ item }}
                                        </span> -->
                                        <span>{{ row.stockCodes.join(',') }}</span>
                                    </div>

                                    <el-tag v-if="row.hasOwnProperty('stockCodes') && row.stockCodes.length > 1" style="cursor: default">
                                        {{ row.stockCodes.length + '个证券' }}</el-tag
                                    >
                                </el-tooltip>
                                <span v-if="row.hasOwnProperty('stockCodes') && row.stockCodes.length === 1">
                                    {{ row.stockCodes[0] }}
                                </span>
                            </template>
                            <template #deviationRatio="{ row }">
                                <el-tooltip :disabled="!row.remark" :content="row.remark" placement="bottom">
                                    <span :style="getCellStyle(row.deviationRatio)">{{ row.deviationRatio || '--' }}</span>
                                </el-tooltip>
                            </template>
                        </RiskTableP>
                    </div>
                </el-card>
            </div>
        </div>

        <!-- <StaticResultSearch
            :staticResultQueryDialogVO="staticResultQueryDialogVO"
            :reqVO="staticResultReqVO"
            @staticResultQueryReturn="staticResultQueryReturn"
            editableTabsValue="first"
            :showErrorType="false"
        >
        </StaticResultSearch> -->
    </div>
</template>
<script lang="ts">
import RiskPagination from '@/common/components/risk-pagination.vue';
import RiskTableP from '@/common/components/risk-table-plus.vue';
import { PageVO, TableConfigVO } from '@/common/vo';
import DictionConstUtil from '@/utils/diction-const-util';
import { downLoadFile } from '@/utils/request';
import { accDiv, accMul, dateFormat, timeFormat } from '@/utils/tools';
import { getSystem, setSystem } from '@/utils/user-util';
import { Component, Vue, Watch } from 'vue-property-decorator';
// import StaticBarAccuracy from './static-comparison/static-bar-accuracy.vue';
import StaticBar from './static-comparison/static-bar.vue';
import * as api from './static-comparison/static-comparison';
import StaticResultPie from './static-comparison/static-result-pie.vue';
// import StaticResultSearch from '@/pages/static/risk-result/static-result-search.vue';
import { DialogVO } from '@yhfin/biz';
import XEUtils from 'xe-utils';

@Component({ name: 'StaticComparison', components: { StaticResultPie, StaticBar, RiskTableP, RiskPagination } })
export default class StaticComparison extends Vue {
    currentBtn: string = 'item';
    tableInfo: any = {
        operateUserName: '',
        operateDateTime: '',
    };
    pieData = {
        item: {
            title: '条目总数',
            name: '条目结果差异概况',
            color: ['#1274cd', '#c02e61'],
            data: [
                { value: 0, name: '一致条目', percent: '62.12%' },
                { value: 0, name: '差异条目' },
            ],
            total: 0,
        },
        detail: {
            title: '明细总数',
            name: '明细结果差异概况',
            color: ['#889add', '#eeadc5'],
            data: [
                { value: 0, name: '一致明细' },
                { value: 0, name: '差异明细' },
            ],
            total: 0,
        },
        'detail-thresholdType': {
            title: '明细总数',
            name: '条目结果触警类型分布',
            color: ['#2bcac8', '#e99b1a', '#7f5eae', '#c31610'],
            data: [
                { value: 0, name: '合规' },
                { value: 0, name: '警告' },
                { value: 0, name: '送审' },
                { value: 0, name: '禁止' },
            ],
            total: 0,
        },
        'detail-type': {
            title: '明细总数',
            name: '明细结果差异类型分布',
            color: ['#ed7270', '#a6a3af', '#49a7dc'],
            // '#5a4672'
            data: [
                { value: 0, name: '恒生&风控明细结果不一致' },
                { value: 0, name: '单恒生有该明细结果' },
                { value: 0, name: '单风控有该明细结果' },
                // { value: 0, name: '恒生&风控都无计算结果' },
            ],
            total: 0,
        },
    };
    specificData = {
        item: {
            failed: [],
            succeed: [],
            tags: [],
            name: ['一致条目', '差异条目'],
            color: ['#1274cd', '#c02e61'],
            data: [],
        },
        detail: {
            failed: [],
            succeed: [],
            tags: [],
            name: ['一致明细', '差异明细'],
            color: ['#889add', '#eeadc5'],
            data: [],
        },
    };

    chartInstanceArr: any[] = [];
    // 'itemTotal', 'branchTotal',
    chartComponent: any[] = ['item', 'detail-thresholdType', 'detail', 'detail-type', 'diffBar'];
    tableConfig: TableConfigVO = {
        rowKey: 'entryCode', // 主键key
        allRowKeys: [], // 所有页数据的key集合
    };
    private tableData: any[] = [];
    riskTypeArr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'P'];
    valuationDatesArr = ['T0', 'T1', 'T2'];
    diffTypeOptions: any[] = [
        { value: '0', label: '恒生&风控计算结果一致' },
        { value: '1', label: '恒生&风控计算结果不一致' },
        { value: '2', label: '单恒生有计算结果' },
        { value: '3', label: '单风控有计算结果' },
        // { value: '4', label: '恒生&风控都无计算结果' },
        // { value: '5', label: '恒生&风控条目不存在' },
        // { value: '6', label: '条目已失效' },
    ];
    diffTypeOptions2: any[] = [
        { value: '0', label: '0' },
        { value: '1', label: '1' },
        { value: '2', label: '2' },
        { value: '3', label: '3' },
    ];
    // 触警类型
    ThresholdTypeArr: any[] = [
        { value: '0', label: '合规' },
        { value: '1', label: '警告' },
        { value: '2', label: '送审' },
        { value: '3', label: '禁止' },
    ];
    tableColumns: any[] = [
        {
            title: '产品代码',
            field: 'fundCode',
            minWidth: 130,
            sortable: true,
            filters: [{ data: '' }],
            filterType: 'search',
        },
        {
            title: '产品名称',
            field: 'fundName',
            minWidth: 130,
            sortable: true,
        },
        {
            title: '估值日期',
            field: 'valuationDate',
            minWidth: 130,
            sortable: true,
            align: 'center',
            filterType: 'funnel',
            filterField: 'valuationDates',
            filters: this.valuationDatesArr.map(item => {
                return {
                    label: item,
                    value: item,
                };
            }),
        },
        {
            title: '证券代码',
            field: 'stockCodes',
            minWidth: 130,
            sortable: true,
            filters: [{ data: '' }],
            filterType: 'search',
            align: 'center',
        },
        {
            title: '证券名称',
            field: 'stockNames',
            minWidth: 130,
            render: value => (value ? value.join(',') : ''),
        },
        {
            title: '条目编号',
            field: 'entryCode',
            minWidth: 130,
            sortable: true,
            filters: [{ data: '' }],
            filterType: 'search',
        },
        {
            title: '风险说明',
            field: 'entryName',
            minWidth: 130,
            sortable: true,
            filters: [{ data: '' }],
            filterType: 'search',
        },
        {
            title: '风控触警类型',
            field: 'thresholdType',
            minWidth: 140,
            sortable: true,
            align: 'center',
            // filters: DictionConstUtil.PojoToList2(DictionConstUtil.EntryType),
            filters: this.ThresholdTypeArr,
            filterType: 'funnel',
            filterField: 'thresholdTypes',
            render: value => (this.ThresholdTypeArr.find(item => item.value == value) || {}).label,
        },
        {
            title: '风控计算结果',
            field: 'calculateValue',
            minWidth: 130,
            sortable: true,
            align: 'right',
        },
        {
            title: '恒生计算结果',
            field: 'hsCalculateValue',
            minWidth: 130,
            sortable: true,
            align: 'right',
        },
        {
            // 注意单位 TODO 保留八位小数
            title: '偏离度(%)',
            field: 'deviationRatio',
            minWidth: 130,
            sortable: true,
            align: 'right',
            // style: (value) => {
            //     const deviationRatio = this.tableQueryParams.deviationRatio;
            //     let color = '';
            //     if (!value || value === '--') {
            //         color = '#f5a43a';
            //     } else if (value && Number(value.replace('%', '')) >= deviationRatio) {
            //         color = 'red';
            //     } else if (value && Number(value.replace('%', '')) < deviationRatio) {
            //         color = '#333';
            //     }
            //     return { color: color };
            // },
        },
        {
            title: '条目类型',
            field: 'riskType',
            minWidth: 130,
            sortable: true,
            filterType: 'funnel',
            filters: this.riskTypeArr.map(item => {
                return {
                    label: item,
                    value: item,
                };
            }),
            filterField: 'riskTypes',
            align: 'center',
        },
        {
            title: '差异类型编号',
            field: 'differenceType',
            sortable: true,
            filterType: 'funnel',
            filters: this.diffTypeOptions2,
            filterField: 'differenceTypes',
            align: 'center',
            minWidth: 160,
            // render: (value, record) => (this.diffTypeOptions.find((item) => item.value == value) || {}).label || '--',
        },
        {
            title: '差异类型说明',
            field: 'differenceInfo',
            sortable: true,
            filters: [{ data: '' }],
            filterType: 'search',
            minWidth: 160,
        },
    ];
    paging: PageVO = {
        total: 0,
        currentPage: 0,
        pageSize: 10,
    };
    pagingItem: PageVO = {
        total: 0,
        currentPage: 0,
        pageSize: 10,
    };
    tableLoading: boolean = false;
    tableQueryParams: any = {
        deviationRatio: '0.5',
        exceedThreshold: true,
        sort: {
            advancedSort: {},
            field: '',
            order: '',
            sortSql: '',
        },
    };

    tableQueryParamsItem: any = {
        deviationRatio: '0.5',
        exceedThreshold: true,
        sort: {
            advancedSort: {},
            field: '',
            order: '',
            sortSql: '',
        },
    };

    compareLoading: boolean = false;
    operateStatus: any = '0';
    timer2: any;

    currentType: string = 'item'; //  item | detail

    tableDataItem: any[] = [];
    tableColumnsItem: any[] = [
        {
            title: '条目编号',
            field: 'entryCode',
            minWidth: 130,
            sortable: true,
            filters: [{ data: '' }],
            filterType: 'search',
        },
        {
            title: '风险说明',
            field: 'entryName',
            minWidth: 130,
            sortable: true,
            filters: [{ data: '' }],
            filterType: 'search',
        },
        {
            title: '风控触警类型',
            field: 'thresholdType',
            minWidth: 140,
            sortable: true,
            align: 'center',
            // filters: DictionConstUtil.PojoToList2(DictionConstUtil.EntryType),
            filters: this.ThresholdTypeArr,
            filterType: 'funnel',
            filterField: 'thresholdTypes',
            render: value => (this.ThresholdTypeArr.find(item => item.value == value) || {}).label,
        },
        {
            title: '条目类型',
            field: 'riskType',
            minWidth: 130,
            sortable: true,
            filterType: 'funnel',
            filters: this.riskTypeArr.map(item => {
                return {
                    label: item,
                    value: item,
                };
            }),
            filterField: 'riskTypes',
            align: 'center',
        },
    ];
    tableLoadingItem: boolean = false;
    private staticResultQueryDialogVO: DialogVO = new DialogVO(); // 查询请求弹框
    // 静态结果请求参数
    private staticResultReqVO: any = {
        calculateDateEnd: XEUtils.toDateString(new Date(), 'yyyyMMdd'),
        calculateDateStart: XEUtils.toDateString(new Date(), 'yyyyMMdd'),
        entryCodes: '',
        entryGroups: [],
        entryKey: '',
        entryNames: [],
        excludeEntryGroup: false,
        fundGroups: [],
        paging: { total: 0, currentPage: 1, totalPage: 0, pageSize: 50 },
        prohibitionDate: '',
        reBankCode: '',
        reFundCode: '',
        reIssueCode: '',
        reStockCode: '',
        resultId: '',
        showNewRecord: '1',
        tradeDateStart: '',
        tradeDateEnd: '',
        triggerTypeList: ['3'],
        precision: false,
        sort: '',
        fundTypes: [],
        fdProductCodes: [],
        // entryNameOr: true,
    };

    async mounted() {
        this.chartComponent.forEach(ele => {
            console.log(this.$refs[ele], 'this.$refs[ele]');
            if (['item', 'detail-thresholdType', 'detail', 'detail-type'].includes(ele)) {
                this.chartInstanceArr.push((this.$refs[ele] as any)[0].chartInstance);
            } else {
                this.chartInstanceArr.push((this.$refs[ele] as any).chartInstance);
            }
        });
        window.addEventListener('resize', this.screenAdapter);
        this.screenAdapter();
        await this.getDeviationValue();
        this.successCompare();
        this.getTableData();

        this.operateStatus = (await this.queryCompareStatus()) || '0';
        if (this.operateStatus === '1') {
            this.timer2 = setInterval(async () => {
                this.operateStatus = (await this.queryCompareStatus()) || '0';
            }, 60000);
        }
    }

    beforeDestroy() {
        if (this.timer2) {
            clearInterval(this.timer2);
            this.timer2 = null;
        }
    }

    @Watch('operateStatus', { immediate: true, deep: true })
    watchOperateStatus(newData, oldData) {
        console.log(newData, oldData, 'operateStatus比对状态');

        if (newData === '1') {
            this.compareLoading = true;
        } else if (newData === '0' && this.timer2) {
            this.successCompare();
            this.compareLoading = false;
            clearInterval(this.timer2);
            this.timer2 = null;
        } else if (newData === '0' && oldData === '1') {
            // 不考虑状态有延迟了
            // this.successCompare();
            // this.compareLoading = false;
            // if (this.timer2) {
            //     clearInterval(this.timer2);
            //     this.timer2 = null;
            // }
        }
    }

    getTableData(): void {
        this.tableLoadingItem = true;
        this.$axios({
            method: 'post',
            url: '/deviation/static/entry/query',
            data: {
                ...this.tableQueryParamsItem,
                // ...this.staticResultReqVO,
                paging: this.pagingItem,
                deviationRatio: this.tableQueryParams.deviationRatio,
                exceedThreshold: this.tableQueryParams.exceedThreshold,
                sort: {
                    field: this.tableQueryParamsItem['field'],
                    order: this.tableQueryParamsItem['order'],
                },
            },
        })
            .then((res: any) => {
                const data = res?.list;
                this.tableDataItem = data?.list || [];
                this.pagingItem.total = data?.total || 0;
            })
            .finally(() => {
                this.tableLoadingItem = false;
            });
    }

    /**
     *  条目结果差异概况（环形图）
     */
    getDifferenceSurvey() {
        this.$axios.get('/deviation/static/difference/survey').then(res => {
            this.pieData['item'].data = res['items'].map(item => {
                return { value: item.itemCount, name: item.itemStatusName };
            });
            this.pieData['item']['total'] = res['total'];
        });

        // api.deviationStaticDifferenceSurvey().then(res => {});
    }

    /**
     * 条目结果明细差异概况（环形图）
     */
    getResultDifferenceSurvey() {
        this.$axios.get('/deviation/static/result/difference/survey').then(res => {
            this.pieData['detail'].data = res['items'].map(item => {
                return { value: item.itemCount, name: item.itemStatusName };
            });
            this.pieData['detail']['total'] = res['total'];
        });
        // api.deviationStaticResultDifferenceSurvey().then(res => {});
    }

    /**
     * 明细结果触警类型分布（环形图）
     */
    getThresholdTypeSurvey() {
        this.$axios.get('/deviation/static/result/thresholdType/survey').then(res => {
            this.pieData['detail-thresholdType'].data = res['items'].map(item => {
                return { value: item.itemCount, name: item.itemStatusName };
            });
            this.pieData['detail-thresholdType']['total'] = res['total'];
        });
        // api.deviationStatiResultThresholdTypeSurvey().then(res => {});
    }

    /**
     * 明细结果差异类型分布（环形图）
     */
    getResultDiffTypeSurvey() {
        this.$axios.get('/deviation/static/result/diffType/survey').then(res => {
            this.pieData['detail-type'].data = res['items'].map(item => {
                return { value: item.itemCount, name: item.itemStatusName };
            });
            this.pieData['detail-type']['total'] = res['total'];
        });
        // api.deviationStaticResultDiffTypeSurvey().then(res => {});
    }

    /**
     * 静态偏离度比对
     */
    handlestaticCompare() {
        this.compareLoading = true;
        api.staticCompare().then(res => {
            // this.compareLoading = false;
            // this.successCompare();
            this.operateStatus = '';
        });
        if (this.timer2) {
            clearInterval(this.timer2);
            this.timer2 = null;
        }
        this.timer2 = setInterval(async () => {
            this.operateStatus = (await this.queryCompareStatus()) || '0';
        }, 60000);
    }

    /**
     * 查询比对状态
     */
    async queryCompareStatus() {
        return new Promise((resolve, reject) => {
            this.$axios({ method: 'get', url: '/deviation/static/status' })
                .then((res: any) => {
                    if (res) {
                        resolve(res.operateStatus);
                    }
                })
                .catch(error => {
                    reject(error);
                });
        });
    }

    /**
     * 比对成功后
     */
    successCompare() {
        this.getDifferenceSurvey();
        this.getThresholdTypeSurvey();
        this.getResultDifferenceSurvey();
        this.getResultDiffTypeSurvey();
        this.getDifferenceBar();
        this.getDifferenceBarByParams();
    }

    /**
     * 各类型条目-条目结果/明细结果差异情况(柱状图)
     */
    getDifferenceBar() {
        this.$axios.post('/deviation/static/difference/bar', { type: this.currentBtn == 'item' ? '0' : '1' }).then(res => {
            // res = {
            //     failed: [0, 1, 2, 3, 5],
            //     failedPercent: ['0%', '1%', '2%', '3%', '5%'],
            //     succeed: [5, 3, 2, 1, 0],
            //     succeedPercent: ['5%', '3%', '2%', '1%', '0%'],
            //     tags: ['C', 'D', 'E', 'F', 'G'],
            // };

            this.specificData[this.currentBtn].succeed = res['succeed'];
            this.specificData[this.currentBtn].succeedPercent = res['succeedPercent'];
            this.specificData[this.currentBtn].failed = res['failed'];
            this.specificData[this.currentBtn].failedPercent = res['failedPercent'];
            this.specificData[this.currentBtn].tags = res['tags'];

            // this.specificData[this.currentBtn].succeed = [123, 456];
            // this.specificData[this.currentBtn].succeedPercent = ['12,5%', '87.5%'];
            // this.specificData[this.currentBtn].failedPercent = ['12,5%', '87.5%'];
            // this.specificData[this.currentBtn].failed = [12, 1];
            // this.specificData[this.currentBtn].tags = ['A', 'B'];
        });
        // api.deviationStaticDifferenceBar({ type: this.currentBtn == 'item' ? '0' : '1' }).then(res => {});
    }
    /**
     * 静态风险偏离度结果查询
     * (后端处理排序和分页)
     */
    getDifferenceBarByParams() {
        this.tableLoading = true;
        let tableQueryParams = this.tableQueryParams;

        // 估值日期"T"特殊处理
        if (tableQueryParams.valuationDates && tableQueryParams.valuationDates.length) {
            tableQueryParams.valuationDates = tableQueryParams.valuationDates.map(item => item.substring(1));
        }
        this.$axios
            .post('deviation/static/query', {
                ...tableQueryParams,
                paging: this.paging,
                // deviationRatio: accDiv(this.tableQueryParams.deviationRatio, 100),
                deviationRatio: this.tableQueryParams.deviationRatio,
                sort: {
                    field: this.tableQueryParams['field'],
                    order: this.tableQueryParams['order'],
                },
            })
            .then((res: any) => {
                if (res) {
                    const data = res?.list;
                    this.tableData = data?.list || [];
                    this.paging.total = data?.total || 0;
                    this.tableInfo = {
                        operateDateTime: dateFormat(res.operateDate) + ' ' + timeFormat(res.operateTime),
                        operateUserName: res.operateUserName || res.operateNo || '--',
                    };
                }
            })
            .finally(() => {
                this.tableLoading = false;
            });
        // api.deviationStaticQuery(this.tableQueryParams).then(res => {});
    }

    /**
     * 获取偏离度
     */
    async getDeviationValue() {
        let values = [];
        // if (!getSystem().length) {
        await new Promise((resolve, reject) => {
            this.$axios
                .get('/systemParam/list')
                .then((res: any) => {
                    values = res;
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });
        // }
        // 偏离度范围设定值
        let param = values.find(item => item.paramKey == 'STATIC_RESULT_DEVIATION_VALUE')?.paramValue || '0.005';
        // this.tableQueryParams.deviationRatio = accMul(param, 100);
        this.tableQueryParams.deviationRatio = param;
        console.log(this.tableQueryParams.deviationRatio, 'this.tableQueryParams.deviationRatio');
    }

    /**
     * 修改偏离度
     */
    // async setDeviationValue() {
    //     let values = getSystem() || [];
    //     let obj = values.find(item => item.paramKey == 'RISK_RESULT_DEVIATION_VALUE');
    //     if (obj) {
    //         obj.paramValue = this.tableQueryParams.deviationRatio / 100;
    //     }
    //     setSystem(values);
    //     // 接口保存
    // }

    timer: any;
    handleDeviationRatio(val: string) {
        this.tableQueryParams.deviationRatio = val.replace(/[^\d.]/g, ''); // 清除“数字”和“.”以外的字符

        // if (this.tableQueryParams.exceedThreshold) {
        //     this.tableQueryParams.exceedThreshold = !this.tableQueryParams.exceedThreshold;
        // }

        const _this = this;
        if (this.timer) {
            clearTimeout(this.timer);
        }
        this.timer = setTimeout(() => {
            _this.getTableData();
            _this.getDifferenceBarByParams();
            _this.timer = undefined;
        }, 1000);
    }

    /**
     * 按钮操作
     */
    handleBtn(type: string) {
        console.log(this.currentBtn, 'currentBtn');
        if (type == 'item') {
            this.currentBtn = type;
            this.getDifferenceBar();
        } else if (type == 'detail') {
            this.currentBtn = type;
            this.getDifferenceBar();
        } else if (type == 'compare') {
            this.handlestaticCompare();
        } else if (type == 'loadout') {
            downLoadFile({
                url: '/deviation/static/export/bigData',
                method: 'post',
                data: {
                    ...this.tableQueryParams,
                    deviationRatio: this.tableQueryParams.deviationRatio,
                    sort: {
                        field: this.tableQueryParams['field'],
                        order: this.tableQueryParams['order'],
                    },
                },
                loading: true,
                loadingMsg: '正在准备导出，请稍后··· ···',
            });
        } else if (type == 'loadout1') {
            if (this.currentType === 'item') {
                downLoadFile({
                    url: '/deviation/static/entry/export',
                    method: 'post',
                    data: {
                        ...this.tableQueryParamsItem,
                        deviationRatio: this.tableQueryParamsItem.deviationRatio,
                        sort: {
                            field: this.tableQueryParams['field'],
                            order: this.tableQueryParams['order'],
                        },
                    },
                    loading: true,
                    loadingMsg: '正在准备导出，请稍后··· ···',
                });
            } else {
                downLoadFile({
                    url: '/deviation/static/export',
                    method: 'post',
                    data: {
                        ...this.tableQueryParams,
                        deviationRatio: this.tableQueryParams.deviationRatio,
                        sort: {
                            field: this.tableQueryParams['field'],
                            order: this.tableQueryParams['order'],
                        },
                    },
                    loading: true,
                    loadingMsg: '正在准备导出，请稍后··· ···',
                });
            }
        }
    }

    // 分页、筛选
    pageChange($event?: any) {
        if ($event && $event.type == 'sort') {
            this.tableQueryParams['field'] = $event['sortField'];
            this.tableQueryParams['order'] = $event['order'];
        }
        this.getDifferenceBarByParams();
    }

    pageChangeItem($event?: any) {
        if ($event && $event.type == 'sort') {
            this.tableQueryParamsItem['field'] = $event['sortField'];
            this.tableQueryParamsItem['order'] = $event['order'];
        }
        this.getTableData();
    }

    changeExceedThreshold() {
        this.getTableData();
        this.getDifferenceBarByParams();
    }

    screenAdapter() {
        // TODO
        const titleFontSize = ((this.$refs.diffBar as any).offsetWidth / 100) * 5.6;
        // 分辨率变化图表配置
        const adapterOption = {
            axisLabel: {
                textStyle: {
                    fontSize: titleFontSize,
                },
            },
            // 柱状条目
            series: [
                {
                    // barWidth: titleFontSize,
                    // 条目文字配置
                    // itemStyle: {
                    //   barBorderRadius: [titleFontSize / 2, titleFontSize / 2, 0, 0],
                    // }
                },
            ],
        };
        console.log(this.chartInstanceArr, 'setOption');
        this.chartInstanceArr.forEach(ele => {
            ele.setOption(adapterOption);
            ele.resize();
        });
    }

    getCellStyle(value: any): any {
        const deviationRatio = this.tableQueryParams.deviationRatio;
        let color = '';
        if (!value || value === '--') {
            color = '#f5a43a';
        } else if (value && Number(value.replace('%', '')) >= deviationRatio) {
            color = 'red';
        } else if (value && Number(value.replace('%', '')) < deviationRatio) {
            color = '#333';
        }
        return { color: color };
    }

    destroyed() {
        window.removeEventListener('resize', this.screenAdapter);
    }

    handleCutTable(type): void {
        this.currentType = type;
    }

    // 查询
    private queryStatic(): void {
        // const title = this.activeValue == 'first' ? '静态结果高级查询' : '静态历史结果高级查询';
        this.staticResultQueryDialogVO = this.staticResultQueryDialogVO.getAddDialog('条目比对结果高级查询');
    }

    // 高级查询返回值
    private staticResultQueryReturn(val): void {
        this.staticResultReqVO = val;
        this.getTableData();
    }
}
</script>
<style lang="scss" scoped>
.com-container {
    height: 100%;
    min-width: 1200px;
    // min-height: 600px;
    .header {
        width: 100%;
        height: 40px;
        background-image: url('./images/title-bgc.png');
        background-size: 100% 100%;
        // background-color: #fff;
        background-repeat: no-repeat;
        position: relative;
        .title {
            // font-size: 24px;
            // // font-family: PingFangSC-Semibold, PingFang SC;
            // font-weight: 600;
            // color: #107fff;
            // line-height: 33px;
            // letter-spacing: 20px;
            // text-align: center;
            // height: 100%;
            // line-height: 60px;
            display: flex;
            overflow: hidden;
            width: 100%;
            height: 100%;
            letter-spacing: 6px;
            align-items: center;
            justify-content: center;
            white-space: nowrap;
            font-family: 'Helvetica Neue';
            color: black;
            font-size: 22px;
            font-weight: bold;
        }
    }
    .operate {
        width: 100%;
        height: 13px;
        text-align: end;
        position: absolute;
        top: 28px;
        bottom: 0;
        background-image: url(./images/operate.png);
        background-size: 100% 100%;
        background-repeat: no-repeat;
    }
    .content {
        height: calc(100% - 40px);
        min-height: 600px;
        padding: 18px 10px 10px;
        display: flex;
        flex-direction: column;
        gap: 10px;
        .pie-content {
            width: 100%;
            height: 32%;
            min-height: 220px;
            display: flex;
            flex-direction: row;
            gap: 10px;
            .pie-content-item {
                width: 21%;
            }
            .pie-content-item-detail-type {
                flex: 1;
            }
            .pie-content-chart {
                height: calc(100% - 25px);
            }
        }

        .bar-content {
            width: 100%;
            height: 28%;
            min-height: 200px;

            .bar-content-chart {
                height: calc(100% - 25px);
            }
            & > div {
                position: relative;
            }
        }
        .table-content {
            width: 100%;
            height: 40%;
            min-height: 370px;
            border: 1px solid #fff;
            .table-content-data {
                width: 100%;
                height: calc(100% - 30px);
                padding: 0 10px;
            }
        }
    }
}

.text {
    padding: 0 10px 3px 10px;
    font-size: 15px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .text-left {
        display: flex;
        .imgStyle {
            height: 20px;
            width: 20px;
            margin-right: 5px;
            background-repeat: no-repeat;
            background-size: 20px 20px;
        }
        .pieImg {
            background-image: url('./images/pie.png');
        }
        .barImg {
            background-image: url('./images/bar.png');
        }
        .tableImg {
            background-image: url('./images/table.png');
        }
        span {
            line-height: 19px;
            // font-weight: bold;// TODO
        }
    }
}

/deep/ .el-card {
    height: 100%;
    .el-card__body {
        padding: 6px 2px 2px !important;
        width: 100%;
        height: 100%;
        background-color: #ebebeb;
    }
}
/deep/ .el-button {
    padding: 6px 18px !important;
}
/deep/ .el-checkbox__input.is-checked + .el-checkbox__label {
    color: #575757;
}
/deep/ .el-checkbox__label {
    padding-left: 4px !important;
}
/deep/ .el-pagination {
    padding: 2px !important;
}

/deep/ .el-pagination .btn-next,
/deep/ .el-pagination .btn-prev {
    background: none;
}
</style>
<style lang="scss">
.tips-popper {
    max-width: 700px;
    max-height: 300px;
    overflow: auto;
}
</style>
